package top.hkyzf.study.leetcode.linkedlist;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 朱峰
 * @date 2022-2-16 9:07
 */
public class 环形链表_141 {
    public boolean hasCycle1(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (!set.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (slow == null || fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

    @Test
    public void testHasCycle () {
        ListNode head = new ListNode();
        ListNode node4 = new ListNode(-4);
        ListNode node3 = new ListNode(0, node4);
        ListNode node2 = new ListNode(2, node3);
        ListNode node1 = new ListNode(3, node2);
        head.next = node1;
        node4.next = node1;
        System.out.println(hasCycle(head));
    }
}
